<?php

namespace App\Http\Controllers;

use App\Events\ArticleView;
use App\Handlers\ImageUploadHandler;
use App\Models\Article;
use App\Models\Category;
use App\Models\Tag;
use App\Models\TagMap;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Requests\ArticleRequest;
use Illuminate\Support\Facades\Redis;
use Auth;
use Illuminate\Support\Facades\DB;


class ArticlesController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth', ['except' => ['index', 'show','goodList','dealTop']]);
    }

	public function index()
	{
		$articles = Article::with('user','category')->orderBy('created_at','desc')->paginate(15);
		$user =User::where(['id'=>1])->first();
		$hotTag = Tag::orderBy('hot','desc')->limit(4)->get();
		$categories = Category::all();
		return view('articles.index', compact('articles','user','categories','hotTag'));
	}

    public function show(Article $article,Tag $tag)
    {
        event(new ArticleView($article));
        //文章标签
        $article->tags = $tag->getTag($article->tags);

        //上下篇
        $prev_article = $article->getPrevArticle();
        $next_article = $article->getNextArticle();
        //相关文章
        $articles  = Article::where('category_id',$article->category_id)
            ->inRandomOrder()
            ->take(10)
            ->select(['id','title'])
            ->get();
        return view('articles.show', compact('article','tags','prev_article','next_article','articles'));
    }

	public function create(Article $article,Tag $tag)
	{
        $categories = Category::all();
        $tags = $tag->getTags();
		return view('articles.create_and_edit', compact('article','tags','categories'));
	}

	public function store(ArticleRequest $request,Article $article)
	{
        $article ->fill($request->all());
        $article->user_id = Auth::id();
        $article->tags = implode(',',$request->tags);
		$article->save();
		return redirect()->to($article->link())->with('success', '新建成功！');
	}

	public function edit(Article $article,Tag $tag)
	{
        $categories = Category::all();
        $tags = $tag->getTags();
        $article->tags = explode(',',$article->tags);
        $this->authorize('update', $article);
		return view('articles.create_and_edit', compact('article','tags','categories'));
	}

	public function update(ArticleRequest $request, Article $article,TagMap $tagMap)
	{
        $article ->fill($request->all());
//        $article->user_id = Auth::id();
        $article->tags = implode(',',$request->tags);
		$article->update();

		return redirect()->to($article->link())->with('success', '更新成功！');
	}

	public function destroy(Article $article)
	{
        DB::table('tag_maps')->where('aid',$article->id)->delete();
        $this->authorize('destroy', $article);
		$article->delete();

		return redirect()->route('articles.index')->with('success', '删除成功！');
	}


	//上下篇
    public function getPrevArticleId($id)
    {
        return Article::where('id', '<', $id)->max('id');
    }
    public function getNextArticleId($id)
    {
        return Article::where('id', '>', $id)->min('id');
    }
	public function uploadImage(Request $request,ImageUploadHandler $uploader)
    {
        // 初始化返回数据,默认失败
        $data = [
            'success' => false,
            'msg'     => '上传失败！',
            'file_path'=>''
        ];
        // 判断是否有上传文件，并赋值给 $file
        if ($file = $request->upload_file) {
            // 保存图片到本地
            $result = $uploader->save($request->upload_file, 'articles', \Auth::id(), 1024);
            // 图片保存成功的话
            if ($result) {
                $data['file_path'] = config('app.url').'/admin/upload/'.$result['path'];
                $data['msg']       = "上传成功!";
                $data['success']   = true;
            }
        }
        return $data;
    }
    public function dealTop(Request $request)
    {
        $article_id = $request->article_id;
        $user_ip = $request->getClientIp();
        $isExist = Redis::sismember('article_id_'.$article_id,$user_ip);
        if ($request->has('top')){
            if ($isExist){
                return json_encode(['code'=>'301','msg'=>"您已经点过赞了哟"]);
            }
            Redis::sadd('article_id_'.$article_id,$user_ip);
            $top  = $request->top+1;
            Article::where(['id'=>$article_id])->update(['top'=>$top]);
        }else{
            $top  = Article::where(['id'=>$article_id])->select('top')->first()['top'];
        }
        return json_encode(['code'=>'200','data'=>['top'=>$top],'msg'=>'success']);
    }
    //test
    public function goodList(Request $request)
    {
        $arr = [
            [
                'goodName'=>'联想拯救者Y7000p',
                'img' =>'https://maxotm.cn/images/1.jpg'
            ],
            [
                'goodName'=>'联想拯救者Y7000p',
                'img' =>'https://maxotm.cn/images/2.jpg'
            ],
            [
                'goodName'=>'联想拯救者Y7000p',
                'img' =>'https://maxotm.cn/images/3.jpg'
            ],[
                'goodName'=>'联想拯救者Y7000p',
                'img' =>'https://maxotm.cn/images/4.jpg'
            ],
            [
                'goodName'=>'联想拯救者Y7000p',
                'img' =>'https://maxotm.cn/images/h1.jpg'
            ],
            [
                'goodName'=>'联想拯救者Y7000p',
                'img' =>'https://maxotm.cn/images/1.jpg'
            ],
            [
                'goodName'=>'联想拯救者Y7000p',
                'img' =>'https://maxotm.cn/images/2.jpg'
            ],
            [
                'goodName'=>'联想拯救者Y7000p',
                'img' =>'https://maxotm.cn/images/3.jpg'
            ],[
                'goodName'=>'联想拯救者Y7000p',
                'img' =>'https://maxotm.cn/images/4.jpg'
            ],
            [
                'goodName'=>'联想拯救者Y7000p',
                'img' =>'https://maxotm.cn/images/h1.jpg'
            ]
            ,
            [
                'goodName'=>'联想拯救者Y7000p'.$request->goodId,
                'img' =>'https://maxotm.cn/images/h1.jpg'
            ]
        ];
        return  json_encode($arr,true);
    }
}